<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="员工名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入员工名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-160px"
        />
      </el-form-item>

      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-160px"
        />
      </el-form-item>

      <el-form-item label="审批状态" prop="checkState">
        <el-select
          v-model="queryParams.checkState"
          placeholder="请选择审批状态"
          clearable
          class="!w-160px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_CHECK_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>

      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="技师编号" align="center" prop="id"/>-->
      <el-table-column label="申请时间" align="center" prop="createTime" :formatter="dateFormatter"/>
      <el-table-column label="员工名称" align="center" prop="name"  />
      <el-table-column label="联系手机号" align="center" prop="mobile"  />
      <el-table-column label="报销类型" align="center" prop="typeName" />
      <el-table-column label="报销金额" align="center" prop="amount" />
      <el-table-column label="审批状态" align="center" prop="checkStateStr" />
      <el-table-column label="审批操作" align="center" prop="checkState" min-width="80">
        <template #default="scope">
          <div :class="['custom-select', { 'priorit1' : scope.row.checkState === 0}]">
            <el-select v-if="scope.row.checkState === 0 || scope.row.checkState === 1 || scope.row.checkState === 2" style="text-align: center;"
                       @change="handleReimburseCheckChange(scope.row)"
                       v-model="scope.row.checkState">
              <el-option
                v-for="dict in checkStateOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-select v-if="scope.row.checkState === 3 || scope.row.checkState === 4 || scope.row.checkState === 5" style="text-align: center;"
                       @change="handleReimburseCheckChange(scope.row)"
                       v-model="scope.row.checkState">
              <el-option
                v-for="dict in repealStateOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="付款状态" align="center" prop="checkState" min-width="80">
        <template #default="scope">
          <div :class="['custom-select', { 'priorit1' : scope.row.payState === 0}]">
            <el-select style="text-align: center;"
                       @change="handleReimbursePayChange(scope.row)"
                       v-model="scope.row.payState">
              <el-option
                v-for="dict in payStateOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="reimburseItemShow(scope.row)"
            v-hasPermi="['erp:finance-reimburse-item:query']"
          >
            明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AttendanceForm ref="formRef" @success="getList"/>


  <el-dialog :title="reimburseItemTitle" v-model="reimburseItemVisible" width="50%">
    <el-table v-loading="loading" :data="reimburseItemList" max-height="500px" :stripe="true" border
              :show-overflow-tooltip="true">
      <el-table-column label="报销类型" align="center" width="150px" prop="typeName"/>
      <el-table-column label="报销费用" align="center" width="150px" prop="amount"/>
      <el-table-column label="报销说明" align="center" width="400px" prop="remark"/>
      <el-table-column label="说明附件" :min-width="100" align="center" prop="invoicesPic">
        <template #default="scope">
          <el-image
            style="width: 20px; height: 20px"
            :src="scope.row.invoicesPic"
            :key="index"
            z-index="1000000"
            :initial-index="index"
            hide-on-click-modal
            preview-teleported
            :preview-src-list="scope.row.invoicesPicList"
          />
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>


</template>

<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import {ReimburseApi, ReimburseVO} from '@/api/erp/finance/reimburse'
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";

/** ERP 请假 列表 */
defineOptions({name: 'Attendance'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const reimburseItemVisible = ref(false)
const reimburseItemList = ref([])
const reimburseItemTitle = ref()
const reimburseId = ref()

const loading = ref(true) // 列表的加载中
const list = ref<ReimburseVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const checkStateOptions = ref([{label: '待审批', value:0},{label: '通过申请', value:1},{label: '拒绝申请', value:2}])
const repealStateOptions = ref([{label: '待审批', value:3},{label: '通过申请', value:4},{label: '拒绝申请', value:5}])
const payStateOptions =[{label: '待付款', value:0},{label: '已付款', value:1}]
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  mobile: undefined,
  storeId: null,
  companyId: null,
  type: null,
  checkState: null,
  checkDesc: null,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


// 获取当前日期
const today = new Date();

// 设置开始时间为当前日期的 00:00:00
const startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);

// 设置结束时间为当前日期的 23:59:59
const endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);

// 将时间格式化为 "年-月-日 时:分:秒"
const formatTime = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const formattedStartTime = ref(formatTime(startTime));
const formattedEndTime = ref(formatTime(endTime));

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ReimburseApi.getReimbursePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}


const reimburseSubmit = async () => {
  let id = reimburseId.value;

  //搜索中 提示
  let loading = ElLoading.service({
    lock: true,
    text: '搜索中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    await ReimburseApi.getReimburseItem(id).then(res => {
      reimburseItemList.value = res;
      console.log(res)
    })
  } finally {
    loading.close();
  }

}

const reimburseItemShow = async (row) => {
  reimburseItemTitle.value = "【" + row.name + "】报销明细";
  reimburseItemVisible.value = true;
  reimburseId.value = row.id;
  reimburseSubmit();
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}


const handleReimbursePayChange = async (row) => {
  for (const key in payStateOptions) {
    if (payStateOptions[key].value === row.payState) {
      await ElMessageBox.confirm(
        '员工【' + row.name + '】付款状态是否修改为【' + payStateOptions[key].label + '】?',
        '付款状态确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await ReimburseApi.updateReimbursePayState(row.id, row.payState);
            ElMessage({
              type: 'success',
              message: '付款状态已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getList()
        })
    }
  }

}

const handleReimburseCheckChange = async (row) => {

  const reimburseCheckOptions = getIntDictOptions(DICT_TYPE.ERP_CHECK_TYPE);

  for (const key in reimburseCheckOptions) {
    if (reimburseCheckOptions[key].value === row.checkState) {

      await ElMessageBox.confirm(
        '员工【' + row.name + '】审批状态是否修改为【' + reimburseCheckOptions[key].label + '】?',
        '审批状态确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await ReimburseApi.updateReimburseCheckState(row.id, row.checkState);
            ElMessage({
              type: 'success',
              message: '审批状态已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getList()
        })
    }
  }

}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ReimburseApi.deleteReimburse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ReimburseApi.exportReimburse(queryParams)
    download.excel(data, 'ERP 请假.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>


<style scoped>
.custom-select .el-input__inner {
  /* 默认颜色 */
  color: #303133;
}

.priorit1 .el-input__inner {
  color: red; /* taskLevel 为 2 时的颜色 */
}

.priorit2 .el-input__inner {
  color: green; /* taskLevel 为 3 时的颜色 */
}

.priorit3 .el-input__inner {
  color: gray; /* taskLevel 为 3 时的颜色 */
}
</style>


